package service

import (
	"day12_30/config"
	"day12_30/internal/api/request"
	"day12_30/internal/api/response"
	"day12_30/internal/models/dao"
	"day12_30/pkg"
	"math/rand"
	"strconv"
	"time"
)

func UserRegister(user *request.UserRegisterRequest) (int, string) {
	password := pkg.Md5(user.Password)
	users := dao.User{
		Tel:      user.Tel,
		Username: user.Tel,
		Password: password,
	}
	err := config.DB.Create(&users).Error
	if err != nil {
		return 0, "注册失败"
	}
	return int(users.ID), ""
}

func UserLogin(user *request.UserLoginRequest) (string, string) {
	if !pkg.Tel(user.Tel) {
		return "", "手机号格式错误"
	}
	Num := "user_send_login" + user.Tel
	var users *dao.User
	get := config.Rdb.Get(config.Ctx, Num)
	if get.Val() == "" {
		return "", "暂未获取短信验证码"
	}
	if get.Val() != user.SendCode {
		return "", "验证码输入错误"
	}
	config.DB.Where("tel=?", user.Tel).Limit(1).Find(&users)
	if users.ID == 0 {
		return "", "登录失败，账户不存在"
	}
	if pkg.Md5(user.Password) != users.Password {
		return "", "登录失败，密码错误"
	}
	handler, _ := pkg.TokenHandler(strconv.Itoa(int(users.ID)))
	config.Rdb.Del(config.Ctx, Num)
	return handler, ""
}

func UserFind(user *request.UserLoginRequest, token string) response.UserLoginResponse {
	var users *dao.User
	config.DB.Where("tel=?", user.Tel).Limit(1).Find(&users)
	userLoginResponse := response.UserLoginResponse{
		Token:    token,
		UserId:   int(users.ID),
		Tel:      users.Tel,
		Username: users.Username,
		Password: users.Password,
	}
	return userLoginResponse
}

func SendMessage(send *request.SendMessage) string {
	Num := "user_send_" + send.Source + send.Tel
	get := config.Rdb.Get(config.Ctx, Num)
	if get.Val() != "" {
		return "请稍后再试"
	}
	i := rand.Intn(9000) + 1000
	/*code, err := pkg.SendCode(send.Tel, strconv.Itoa(i))
	if err != nil {
		return "短信发送失败"
	}
	if *code.Body.Code != "ok" {
		return *code.Body.Message
	}*/
	config.Rdb.Set(config.Ctx, Num, i, time.Minute*3)
	return ""
}
